package com.itheima.servlet;

import com.itheima.mapper.UserMapper;
import com.itheima.pojo.User;
import com.itheima.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 解决POST乱码
        request.setCharacterEncoding("UTF-8");

        // 1. 接收用户数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        // 2. 调用Mapper 根据用户名查询，返回User对象
        User user = mapper.selectByUsername(username);

        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();

        // 3. 判断User对象是否为 null
        if (user == null) {
            // 为null：用户名可用
            User registerUser = new User();
            registerUser.setUsername(username);
            registerUser.setPassword(password);

            int row = mapper.add(registerUser);
            sqlSession.commit();
            if (row > 0) {
                // 注册成功
                writer.write("<h1>恭喜您, " + username + "注册成功</h1>");
            } else {
                // 注册失败
                writer.write("<h1>服务器繁忙!请稍后再试!</h1>");
            }
        } else {
            // 不为null：用户名重复
            writer.write("<h1>骚年, " + username + "已经存在,请重新注册</h1>");
        }
    }
}
